<template>
  <div class="page-box">
    <van-nav-bar
      title="用车"
      right-text="刷新"
      fixed
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <div class="content">
      <van-notice-bar text="由于路况实时变化，预估价可能存在波动，仅供参考" />
      <van-tabs v-model:active="activeName" @change="getShowCarType">
        <van-tab
          v-for="(item, i) in ENUMS.CarType"
          :key="i + 'carType'"
          :title="item.values ? item.label : '全部车型'"
          :name="item.values"
        ></van-tab>
      </van-tabs>
      <div class="car-list" v-if="Object.keys(showCar).length">
        <template v-for="(list, key) in showCar" :key="key + 'caro'">
          <div class="type-mode">
            <div class="car-types" v-show="Object.keys(showCar).length > 1">
              {{ getCarTypeName(key) }}
              <span style="font-size: 10px">({{ list.length }})</span>
            </div>
            <template v-for="(jtem, j) in list" :key="j + 'carl'">
              <div class="car-item">
                <van-row>
                  <van-col span="10" class="item-left">
                    <img :src="jtem.car_source_img" alt="" class="comp-logo" />
                    <div class="comp-info-box">
                      <span class="comp-name">{{ jtem.car_source }}</span>
                      <p class="comp-info">{{ jtem.price_tip }}</p>
                    </div>
                  </van-col>
                  <van-col span="14" class="item-right">
                    <span class="comp-price">
                      预估：
                      <h1>{{ jtem.estimate_price }}</h1>
                      元
                    </span>
                    <van-button
                      @click="open_order_car(jtem)"
                      type="primary"
                      color="#FE8F00"
                      size="small"
                      >{{ btnName }}</van-button
                    >
                  </van-col>
                </van-row>
              </div>
            </template>
          </div>
        </template>
      </div>
      <div v-else class="no-data">
        <van-empty description="未匹配到该车型" />
      </div>
    </div>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, toRefs } from "vue";
import ENUMS from "../../assets/enum/searchCar";

export default {
  name: "CarInfo",
  setup() {
    const { proxy } = getCurrentInstance();
    const pageData = reactive({
      activeName: "",
      btnName: "立即用车",
      param: {},
      carList: [],
      car: {},
      showCar: {}
    });
    onMounted(() => {
      pageMethods.initQuery();
    });
    const pageMethods = {
      initQuery() {
        // 初始化搜索参数
        const searchParam = proxy.$store.state.searchParam;
        // 设置按钮名字
        if (searchParam.searchType != "1") {
          pageData.btnName = "预约用车";
        }

        if (JSON.stringify(searchParam) === "{}") {
          proxy.$router.push({
            path: "/home"
          });
          return;
        }
        let param = {
          service_type: searchParam.searchType || "", // 服务类型 1:实时 2:预约 3:接机 4送机
          city_district: searchParam.from_address_ALL.code || "", // 城市区号 例如：010:北京 027:武汉
          passenger_phone: searchParam.mans.member_phone || "",
          flat: searchParam.from_address_ALL.flat || "",
          flng: searchParam.from_address_ALL.flng || "",
          tlat: searchParam.to_address_ALL.flat || "",
          tlng: searchParam.to_address_ALL.flng || "",
          from_address: searchParam.from_address_ALL.address || "",
          to_address: searchParam.to_address_ALL.address || "",
          car_source: "0", // 用车平台  多个竖线分割 ”0|1|2“
          require_level: pageData.activeName // 车型
        };
        // 送机其实就是预约用车
        if (["2", "4"].includes(searchParam.searchType)) {
          param.service_type = "2";
          // 用车时间
          param.departure_time = searchParam.departure_time || "";
        } else if (searchParam.searchType == "3") {
          // 航班号
          param.air_code = searchParam.air_code || "";
          // 机场三字码
          param.arrive_air_port_code = searchParam.flight_arrcode || "";
          // 航班到达时间
          param.flt_takeoff_time = searchParam.departure_time || "";
        }
        // {
        //     "arrive_air_port_code": "non ea incididunt in aliquip", // 接机机场三字码，接送机必传
        //     "flt_takeoff_time": "Lorem", // 航班起飞时间，接送机必传(yyyy-MM-dd HH:mm:ss)
        //     "air_code": "reprehenderit", // 航班号，接送机必传
        //     "departure_time": "ullamco" // 用车时间，预约单必传(yyyy-MM-dd HH:mm:ss)
        // }

        // let param = {
        //   service_type: "1",
        //   city_district: "027",
        //   passenger_phone: "15688133182",
        //   flat: 30.438271,
        //   flng: 114.455314,
        //   tlat: 30.502113,
        //   tlng: 114.384166,
        //   from_address: "佛祖岭F区",
        //   to_address: "康卓新城(东北门)",
        //   car_source: "0",
        //   require_level: ""
        // };
        pageData.param = param;
        pageMethods.getCarList();
      },
      onClickLeft() {
        proxy.$router.back();
      },
      onClickRight() {
        pageMethods.getCarList();
      },
      async getCarList(carType) {
        pageData.param.require_level = carType || "";
        const res = await proxy.$axiosJson(
          "/security/v1/icardcOrder/queryEstimatePrice",
          pageData.param
        );
        pageData.carList =
          (res.data || {})["car_estimate_price_bean_list"] || [];
        pageMethods.carTypes();
        pageMethods.getShowCarType();
      },
      getCarTypeName(key) {
        return ENUMS.getEnumvalues("CarType", key)["label"] || "其他车型";
      },
      carTypes() {
        // 将用车类型进行分组
        const o = {};
        pageData.carList.forEach(item => {
          const t = item.car_level || "other";
          if (o[t]) {
            o[t].push(item);
          } else {
            o[t] = [item];
          }
        });
        // 对车型里面的金额进行排序
        for (let key in o) {
          o[key].sort((a, b) => {
            return (a["estimate_price"] || 0) - (b["estimate_price"] || 0);
          });
        }
        pageData.car = o;
        // Object.keys(o).length
      },
      getShowCarType() {
        const COPYCAR = JSON.parse(JSON.stringify(pageData.car));
        pageData.showCar = {};
        if (!pageData.activeName) {
          pageData.showCar = COPYCAR;
          console.log(pageData.showCar);
          return;
        }
        if (COPYCAR[pageData.activeName])
          pageData.showCar = {
            [pageData.activeName]: COPYCAR[pageData.activeName]
          };
        console.log(pageData.showCar);
      },
      open_order_car(item) {
        // 设置是否超标（因为没对接差标  所以这个默认为未超标）
        item.overproof = "0";

        proxy.$store.commit("SET_CAR_INFO", item);
        // 打开用车预定页面
        proxy.$router.push({
          path: "/reserveOrder"
        });
      }
    };
    return {
      ...toRefs(pageData),
      ...pageMethods,
      ENUMS
    };
  }
};
</script>

<style scoped lang="less">
.page-box {
  padding: 7px;
  height: 100%;
  background: #ffffff;
  .content {
    margin-top: 1.22667rem;
    .type-mode {
      background: #ffffff;
      margin-top: 10px;
      border-radius: 8px;
      .car-types {
        font-size: 16px;
        padding: 10px;
        color: #000000;
        font-weight: bold;
      }
      .car-item {
        font-size: 15px;
        padding: 13px 10px;
        border-top: 1px solid #eeeeee;
        :deep(.item-left) {
          .comp-logo {
            width: 35px;
            height: 35px;
            vertical-align: top;
          }
          .comp-info-box {
            display: inline-block;
            padding-left: 6px;
            font-size: 15px;
            color: #333333;
            width: calc(100% - 37px);
            vertical-align: bottom;
            p {
              font-size: 12px;
              word-break: break-all;
              color: darkgoldenrod;
              margin-top: 7px;
            }
          }
        }
        :deep(.item-right) {
          text-align: right;
          .comp-price {
            display: inline-block;
            font-size: 14px;
            color: #999999;
            min-width: 130px;
            text-align: left;
            h1 {
              color: #333333;
              display: inline;
              font-size: 16px;
              font-weight: 600;
            }
          }
        }
      }
    }
  }
}
.no-data {
  background: #ffffff;
}
</style>
